package no.eirikb.bomberman.server;

import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import no.eirikb.bomberman.applet.game.Bomb;

/**
 *
 * @author eirikb
 */
public class BombHandler extends Thread {

    private BombermanServer server;
    private ArrayList<Bomb> bombs;
    private final int SLEEPTIME = 1000; //ms to sleep for each bomb countdown

    public BombHandler(BombermanServer server, GameHandler gameHandler) {
        this.server = server;
        bombs = new ArrayList<Bomb>();
    }

    public void addBomb(Bomb bomb) {
        bombs.add(bomb);
    }

    @Override
    public void run() {
        while (true) {
            Bomb[] bl = bombs.toArray(new Bomb[0]);
            for (Bomb bomb : bl) {
                if (bomb.explode()) {
                    bombs.remove(bomb);
                    chainReaction(bomb);
                    server.explodeBomb(bomb);
                }
            }
            try {
                sleep(SLEEPTIME);
            } catch (InterruptedException ex) {
                Logger.getLogger(BombHandler.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    private void chainReaction(Bomb bomb) {
        Bomb[] bl = bombs.toArray(new Bomb[0]);
        for (Bomb b : bl) {
            if (b != bomb) {
                if (bomb.compareTo(b) == 1) {
                    bombs.remove(b);
                    b.setTime(-1);
                    chainReaction(b);
                }
            }
        }
    }
}
